package com.free.dialog;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

/**
 * <p>
 * Title: Eclipse Plugin Development
 * </p>
 * <p>
 * Description: Free download
 * </p>
 * <p>
 * mail: ganshm@gmail.com
 * </p>
 */

public class ChooseDirectoryDialogExample
{
    /**
     * Runs the application
     */
    public void run()
    {
        Display display = new Display();
        Shell shell = new Shell(display);
        shell.setText("Directory Browser");
        createContents(shell);
        shell.pack();
        shell.open();
        while (!shell.isDisposed())
        {
            if (!display.readAndDispatch())
            {
                display.sleep();
            }
        }
    }
    
    /**
     * Creates the window contents
     * 
     * @param shell the parent shell
     */
    private void createContents(final Shell shell)
    {
        shell.setLayout(new GridLayout(6, true));
        new Label(shell, SWT.NONE).setText("Directory:");
        
        // Create the text box extra wide to show long paths
        final Text text = new Text(shell, SWT.BORDER);
        GridData data = new GridData(GridData.FILL_HORIZONTAL);
        data.horizontalSpan = 4; // Text占用4列
        text.setLayoutData(data);
        
        // Clicking the button will allow the user
        // to select a directory
        Button button = new Button(shell, SWT.PUSH);
        button.setText("Browse...");
        button.addSelectionListener(new SelectionAdapter()
        {
            public void widgetSelected(SelectionEvent event)
            {
                // 新建目录对话框
                DirectoryDialog dlg = new DirectoryDialog(shell);
                // 设置初始路径
                dlg.setFilterPath(text.getText());
                // 设置对话框标题
                dlg.setText("SWT's DirectoryDialog");
                // 设置提示信息
                dlg.setMessage("Select a directory");
                // 打开对话框，返回目录
                String dir = dlg.open();
                if (dir != null)
                {
                    // Set the text box to the new selection
                    text.setText(dir);
                }
            }
        });
    }
    
    /**
     * The application entry point
     * 
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        new ChooseDirectoryDialogExample().run();
    }
}
